package com.yupi.yupao.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热任务
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate redisTemplate;

    private List<Long> mainUserList = Arrays.asList(1L);

    @Scheduled(cron = "0 40 23 * * *")
    public void doCacheRecommendUser(){
        RLock lock = redissonClient.getLock("yupao:user:recommend:docache:lock");
        try {
            //只有一个线程能获取到锁
            if(lock.tryLock(0,30000,TimeUnit.MILLISECONDS)) {
                ValueOperations valueOperations = redisTemplate.opsForValue();
                for (Long userId : mainUserList) {
                    String redisKey = String.format("yupao:user:recommend:%s", userId);
                    //无缓存查数据
                    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    Page<User> page = userService.page(new Page<>(1, 20), lambdaQueryWrapper);
                    //写缓存
                    try {
                        valueOperations.set(redisKey, page, 10000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis key is error");
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error!",e);
        }finally {
            //只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                System.out.println("unlock");
                lock.unlock();
            }
        }
    }

}
